package com.yaorange.jk.service.impl;

import com.yaorange.jk.dao.BaseDao;
import com.yaorange.jk.entity.Role;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.entity.UserInfo;
import com.yaorange.jk.service.RoleService;
import com.yaorange.jk.service.UserService;
import com.yaorange.jk.utils.Encrypt;
import com.yaorange.jk.utils.MailUtils;
import com.yaorange.jk.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @author coach tam
 * @date 2017/11/1
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private BaseDao<User,String> userDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BaseDao<UserInfo,String> userInfoDao;
    @Override
    @Transactional(readOnly = true)
    public Pagination findPage(int pageNo, int pageSize) {
        return userDao.pageByHql("from User",pageNo,pageSize);
    }


    @Override
    public List<User> findAll() {
        return userDao.getListByHQL("from User");
    }

    @Override
    public User active(User model) {
        User u = userDao.getByHQL("from User u where id = ? and u.userInfo.code = ?",model.getId(),model.getUserInfo().getCode());
        if(u!=null){
            u.setState(1L);
            u.getUserInfo().setCode(null);
            userDao.update(u);
            }
        return u;
    }

    @Override
    public void save(User user) {

        user.getUserInfo().setUser(user);
        userDao.save(user);

    }

    @Override
    public User findById(String id) {
        return userDao.get(User.class,id);
    }

    @Override
    public void update(User model) {
        //根据主键查询出老数据
        User oldUser = userDao.get(User.class,model.getId());
        oldUser.setUserName(model.getUserName());
        oldUser.setDept(model.getDept());
        oldUser.setState(model.getState());
        userDao.update(oldUser);
    }

    @Override
    public void deleteByIds(String[] ids) {
        for (String id :ids)
        {
            userDao.deleteById(User.class,id);
        }
    }

    @Override
    public void updateRole(String id, String[] roleIds) {
        User user = userDao.get(User.class,id);
        //将String[] roleIds -->Set<Role>
        Set<Role> roleSet = new HashSet<>(roleIds.length);
        for (String roleId: roleIds) {
            Role role = roleService.findById(roleId);
            roleSet.add(role);
        }
        user.setRoleSet(roleSet);

        userDao.update(user);
    }

    @Override
    public User finfindByUsername(String username) {
        User u = userDao.getByHQL("from User where userName = ?", username);
        return u;
    }
}
